package com.zdkj.daemon.quartz.task;

import com.zdkj.common.core.constant.SecurityConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.daemon.quartz.constant.enums.PigxQuartzEnum;
import com.zdkj.daemon.quartz.feign.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import  com.zdkj.daemon.quartz.util.JdbcUtil;

import java.time.LocalDateTime;
import java.util.Calendar;

/**
 * @support: 定时任务对外方法封装类
 * @author: cui_com
 * @version: 1.0
 * @Date: 2020-01-31 17:23
 * @Description: <p>
 *
 * </p>
 */
@Slf4j
@Component("feginTask")
public class FeginTask {

    @Autowired
    private RemoteSubwaySupportService remoteSubwaySupportService;
    @Autowired
    private RemoteSubwayStmService remoteSubwayStmService;
    @Autowired
    private RemoteSubwayStService remoteSubwayStService;
    @Autowired
    private RemoteUpmsService remoteUpmsService;
    @Autowired
    private RemoteSubwayCheckService remoteSubwayCheckService;
    @Autowired
    private RemoteSubwayRcaService remoteSubwayRcaService;

    /**
     * 票务日志自动归档
     * @return
     */
    @SneakyThrows
    public String recordByLogSet() {
        R result = remoteSubwaySupportService.recordByLogSet(SecurityConstants.FROM_IN);
        log.info("执行于:{}，输出{}", LocalDateTime.now(), result.toString());
        return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }

    /**
     * 每日自动生成车站人员在岗记录
     *
     * @return
     */
    @SneakyThrows
    public String saveDaiyPersonRecord() {
        R result = remoteSubwaySupportService.saveDaiyPersonRecord(SecurityConstants.FROM_IN);
        log.info("执行于:{}，输出{}", LocalDateTime.now(), result.toString());
        return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }
    /**
     * 计算车站结存
     * @return
     */
    @SneakyThrows
    public String getTimerSave() {
        R result = remoteSubwayStmService.getTimerSave(SecurityConstants.FROM_IN);
        log.info("执行于:{}，输出{}", LocalDateTime.now(), result.toString());
        return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }
    /**
     * 更改调票申请办理状态
     *
     * @param from 调用标志
     * @return R
     */

    @SneakyThrows
    public String changeHandle() {
        R result = remoteSubwayStmService.changeHandle(SecurityConstants.FROM_IN);
        log.info("执行于:{}，输出{}", LocalDateTime.now(), result.toString());
        return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }
    /**
     * 单程票流失率统计
     * @param from
     * @return
     */

    @SneakyThrows
    public String calcOneWay() {
        R result = remoteSubwayStmService.calc(SecurityConstants.FROM_IN);
        log.info("执行于:{}，输出{}", LocalDateTime.now(), result.toString());
        return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }
    
    /**
     * 车站库存日报表计算，计算前一天
     * @param from
     * @return
     */

    @SneakyThrows
    public String calcStationDaily() {
        R result = remoteSubwayStmService.calcStationDaily(SecurityConstants.FROM_IN);
        log.info("执行于:{}，输出{}", LocalDateTime.now(), result.toString());
        return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }

    /**
     * 每月月初统计上月的公务票金额(财务对账模块)
     *
     * @return
     */
    @SneakyThrows
    public String calcTicketCountMoney() {
        R result = remoteSubwayStService.calcTicketCountMoney(SecurityConstants.FROM_IN);
        log.info("执行于:{}，输出{}", LocalDateTime.now(), result.toString());
        return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }

    /**
     * 统计前一天的车票售卖详情数据
     *
     * @return
     */
    @SneakyThrows
    public String calcSellDaily() {
        R result = remoteSubwayStmService.calcSellDaily(SecurityConstants.FROM_IN);
        log.info("执行于:{}，输出{}", LocalDateTime.now(), result.toString());
        return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }

    /**
     * 车票配入自动确认
     *
     * @return
     */
    @SneakyThrows
    public String ticketAutoConfirm() {
        R result = remoteSubwayStService.ticketAutoConfirm(SecurityConstants.FROM_IN);
        log.info("执行于:{}，输出{}", LocalDateTime.now(), result.toString());
        return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }

    /**
     * 系统日志自动归档
     *
     * @return
     */
    @SneakyThrows
    public String recordExpireSysLogByLogSet() {
        R result = remoteUpmsService.recordExpireByLogSet(SecurityConstants.FROM_IN);
        log.info("执行于:{}，输出{}", LocalDateTime.now(), result.toString());
        return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }
    /**
     * 系统自动按照结算周期进行TVM结算
     *
     * @return
     */
    @SneakyThrows
    public String calcIncomeSettle() {
        R result = remoteSubwayStmService.calcIncomeSettle(SecurityConstants.FROM_IN);
        log.info("执行于:{}，输出{}", LocalDateTime.now(), result.toString());
        return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }
    /**
     * 系统自动按照结算周期进行BOM结算
     *
     * @return
     */
    @SneakyThrows
    public String calcBomSettle() {
        R result = remoteSubwayStmService.calcBomSettle(SecurityConstants.FROM_IN);
        log.info("执行于:{}，输出{}", LocalDateTime.now(), result.toString());
        return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }
    /**
     * 定时任务自动统计车站营收日报表数据
     *
     * @return
     */
    @SneakyThrows
    public String calcStationIncomeDailyReport() {
        R result = remoteSubwayStmService.calcIncomeDailyReport(SecurityConstants.FROM_IN);
        log.info("执行于:{}，输出{}", LocalDateTime.now(), result.toString());
        return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }
	  /**
     * 系统自动执行各个线路和车站的结算周期更新
     *
     * @return
     */
    @SneakyThrows
    public String updateSettlePeriodDate() {

		StringBuilder sb = new StringBuilder();
        StringBuilder sbnew = new StringBuilder();
		StringBuilder sbAdd = new StringBuilder();
		sbAdd.append("insert into subway.sw_ck_data_submit_log ")
             .append("(RELATION_ID,LINE_CODE,STATION_CODE,BEGIN_TIME,END_TIME,SETTLEMENT_TERM,SUBMIT_TIME) ")
             .append(" select a.ID,a.LINE_CODE,a.STATION_CODE,a.BEGIN_TIME,a.END_TIME,st.SETTLEMENT_TERM,now() ")
             .append(" from subway.sw_ck_data_submit a,(  ")
		     .append(" select a.LINE_CODE,a.CODE,ifnull(b.TVM_SETTLEMENT_TERM,1) TVM_SETTLEMENT_TERM,ifnull(b.BOM_SETTLEMENT_TERM,1) BOM_SETTLEMENT_TERM,ifnull(b.SETTLEMENT_TERM,1) SETTLEMENT_TERM  ")
		     .append(" from subway.sw_param_station a ")
		     .append(" left join (select * from subway.sw_pm_long_period_settlement where DEL_FLAG = '0') b on a.LINE_CODE = b.LINE_CODE  and a.CODE = b.STATION_CODE ")
             .append(") st ")
             .append(" where a.LINE_CODE = st.LINE_CODE and a.STATION_CODE = st.CODE and datediff(now(),a.END_TIME)=st.SETTLEMENT_TERM");
		
		if(isFirstDayofMonth(Calendar.getInstance())){//月初第一天
		    sb.append("update subway.sw_ck_data_submit a ")
			  .append("set a.BEGIN_TIME=date_add(a.END_TIME,interval 1 second),a.END_TIME=date_format(now(),'%Y-%m-%d 01:59:59'),a.SUBMIT_TIME=now();"); 
		    
			sbnew.append("insert into subway.sw_ck_data_submit ")
            .append("( LINE_CODE,STATION_CODE,BEGIN_TIME,END_TIME,STATUS,SUBMIT_PERSON_ID,SUBMIT_PERSON_CODE,SUBMIT_PERSON_NAME,SUBMIT_TIME," +
                    "CREATOR_ID,CREATOR_NAME,CREATE_TIME)")
            .append("select st.LINE_CODE,st.CODE,")
            .append("ifnull(date_add(a.END_TIME,interval 1 second),date_format(date_add(now(),interval -1 day),'%Y-%m-%d 02:00:00')),date_format(now(),'%Y-%m-%d 01:59:59'),")
            .append("1,0,'0','',now(),0,'',now() ")
            .append("from ")
            .append("(select a.LINE_CODE,a.CODE,ifnull(b.TVM_SETTLEMENT_TERM,1) TVM_SETTLEMENT_TERM,ifnull(b.BOM_SETTLEMENT_TERM,1) BOM_SETTLEMENT_TERM,ifnull(b.SETTLEMENT_TERM,1) SETTLEMENT_TERM " +
                            "from subway.sw_param_station a left join (select * from subway.sw_pm_long_period_settlement where DEL_FLAG = '0') b on a.LINE_CODE = b.LINE_CODE  and a.CODE = b.STATION_CODE " +
                    "where concat(Lpad(a.LINE_CODE,2,'0'),Lpad(a.CODE,2,'0')) not in (select concat(Lpad(LINE_CODE,2,'0'),Lpad(STATION_CODE,2,'0') ) from subway.sw_ck_data_submit) " +
                    " and  a.LINE_CODE in(select code from subway.sw_param_line where serviceid='1'))")  //追加不是西安地铁线路和站点的新增--todo test
            .append(" st ")
            .append("left join subway.sw_ck_data_submit a on st.LINE_CODE = a.LINE_CODE and st.CODE=a.STATION_CODE;");	
		}else{
		  sb.append("update subway.sw_ck_data_submit a,(")
		  .append(" select a.LINE_CODE,a.CODE,ifnull(b.TVM_SETTLEMENT_TERM,1) TVM_SETTLEMENT_TERM,ifnull(b.BOM_SETTLEMENT_TERM,1) BOM_SETTLEMENT_TERM,ifnull(b.SETTLEMENT_TERM,1) SETTLEMENT_TERM ")
		  .append("from subway.sw_param_station a ")
		  .append("left join (select * from subway.sw_pm_long_period_settlement where DEL_FLAG = '0') b on a.LINE_CODE = b.LINE_CODE  and a.CODE = b.STATION_CODE ")
          .append(") st ")
          .append("set a.BEGIN_TIME=date_add(a.END_TIME,interval 1 second),a.END_TIME=date_add(a.END_TIME,interval st.SETTLEMENT_TERM day),")
          .append("SUBMIT_TIME = now() ")
          .append("where a.LINE_CODE = st.LINE_CODE and a.STATION_CODE = st.CODE and datediff(now(),a.END_TIME)=st.SETTLEMENT_TERM;");
        sbnew.append("insert into subway.sw_ck_data_submit ")
            .append("( LINE_CODE,STATION_CODE,BEGIN_TIME,END_TIME,STATUS,SUBMIT_PERSON_ID,SUBMIT_PERSON_CODE,SUBMIT_PERSON_NAME,SUBMIT_TIME," +
                    "CREATOR_ID,CREATOR_NAME,CREATE_TIME)")
            .append("select st.LINE_CODE,st.CODE,")
            .append("ifnull(date_add(a.END_TIME,interval 1 second),date_format(date_add(now(),interval -1 day),'%Y-%m-%d 02:00:00')),ifnull(date_add(a.BEGIN_TIME,interval st.SETTLEMENT_TERM day),date_format(now(),'%Y-%m-%d 01:59:59')),")
            .append("1,0,'0','',now(),0,'',now() ")
            .append("from ")
            .append("(select a.LINE_CODE,a.CODE,ifnull(b.TVM_SETTLEMENT_TERM,1) TVM_SETTLEMENT_TERM,ifnull(b.BOM_SETTLEMENT_TERM,1) BOM_SETTLEMENT_TERM,ifnull(b.SETTLEMENT_TERM,1) SETTLEMENT_TERM " +
                            "from subway.sw_param_station a left join (select * from subway.sw_pm_long_period_settlement where DEL_FLAG = '0') b on a.LINE_CODE = b.LINE_CODE  and a.CODE = b.STATION_CODE " +
                    "where concat(Lpad(a.LINE_CODE,2,'0'),Lpad(a.CODE,2,'0')) not in (select concat(Lpad(LINE_CODE,2,'0'),Lpad(STATION_CODE,2,'0') ) from subway.sw_ck_data_submit) " +
                    " and  a.LINE_CODE in(select code from subway.sw_param_line where serviceid='1'))")  //追加不是西安地铁线路和站点的新增  -todo test
            .append(" st ")
            .append("left join subway.sw_ck_data_submit a on st.LINE_CODE = a.LINE_CODE and st.CODE=a.STATION_CODE;");
		}		
		
		
		try {
			int iResultAdd = JdbcUtil.exeSqlCrud(sbAdd.toString());
            int iResult = JdbcUtil.exeSqlCrud(sb.toString());
            int iResult2 = JdbcUtil.exeSqlCrud(sbnew.toString());
            //R result = remoteSubwayStmService.calcBomSettle(SecurityConstants.FROM_IN);
            log.info("结算周期更新执行于:{}，输出{}", LocalDateTime.now(), iResult);
        }catch (Exception e) {
            log.error("结算周期自动更新失败！",e);
        }
        return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }

	private static boolean isFirstDayofMonth(Calendar calendar){
	    if (calendar == null) {
	        throw new IllegalArgumentException("Calendar cannot be null.");
	    }

	    int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
	    return dayOfMonth == 1;
	}

	 /**
     * 定时任务  自动提交TVM和BOM数据
     *
     * @return
     */
    @SneakyThrows
    public String autoSubmitTvm() {
        R result = remoteSubwayCheckService.autoSubmitTvm(SecurityConstants.FROM_IN);
        log.info("执行于:{}，输出{}", LocalDateTime.now(), result.toString());
        return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    } 	

	/**
     * 自动提交互联网售票机记录表
     * @param
     * @return
     */
	 
    @SneakyThrows
    public String autoSubmitInternet() {
        R result = remoteSubwayCheckService.autoSubmitInternet(SecurityConstants.FROM_IN);
        log.info("执行于:{}，输出{}", LocalDateTime.now(), result.toString());
        return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }

    /**
     * 文件上传自动解析
     *
     * @return
     */
    @SneakyThrows
    public String autoUploadFileResolve() {
        R result = remoteSubwayRcaService.autoUploadFileResolve(SecurityConstants.FROM_IN);
        log.info("执行于:{}，输出{}", LocalDateTime.now(), result.toString());
        return PigxQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }
}
